#![allow(dead_code)]

use std::collections::HashMap;
use std::io::Write;
use std::net::TcpStream;
use std::sync::{Arc, Mutex};

use away_mq_core::message::PayloadMessage;

#[derive(Debug, Clone, Default)]
pub struct Client {
    items: Arc<Mutex<HashMap<String, TcpStream>>>,
}

impl Client {
    pub fn get_client(&mut self, id: &str) -> TcpStream {
        let binding = self.items.lock().unwrap();
        let client = binding.get(id).unwrap();
        client.try_clone().unwrap()
    }
    pub fn set_client(&mut self, id: &str, client: TcpStream) {
        let mut binding = self.items.lock().unwrap();
        binding.insert(id.to_owned(), client);
    }
    pub fn remove_client(&mut self, id: &str) {
        self.items.lock().unwrap().remove(id).unwrap();
    }

    pub fn send(&mut self, id: &str, payload: PayloadMessage) {
        let mut client = self.get_client(id);
        client.write_all(payload.serialize().as_bytes()).unwrap();
    }
    pub fn send_all(&mut self, payload: &PayloadMessage) {
        let binding = self.items.lock().unwrap();
        for (_id, mut client) in binding.iter() {
            client.write_all(payload.serialize().as_bytes()).unwrap();
        }
    }
}
